import Foundation
import CommonCrypto

class CSETIU {
    private let keyData: Data
    private let ivData: Data
    
    // 16字节密钥（128位）
    private let customKey = "MyCustomKey12346" // 长度为16字符
    
    // 16字节偏移量（128位）
    private let customIV = "MyCustomIV123456" // 长度为16字符
    
    init?() {
        // 将密钥和偏移量转换为 Data
        let keyData = Data(customKey.utf8)
        let ivData = Data(customIV.utf8)
        
        // 检查密钥和偏移量的长度
        guard keyData.count == kCCKeySizeAES128, ivData.count == kCCBlockSizeAES128 else {
            print("密钥或偏移量的字节数不正确: 密钥长度=\(keyData.count), 偏移量长度=\(ivData.count)")
            return nil
        }
        
        self.keyData = keyData
        self.ivData = ivData
    }
    
    func encryptString(_ input: String) -> String? {
        guard let data = input.data(using: .utf8) else { return nil }
        guard let encryptedData = performCrypt(data: data, operation: CCOperation(kCCEncrypt)) else { return nil }
        return encryptedData.map { String(format: "%02hhx", $0) }.joined()
    }
    
    func decryptString(_ hexString: String) -> String? {
        guard let data = dataFromHex(hexString) else { return nil }
        guard let decryptedData = performCrypt(data: data, operation: CCOperation(kCCDecrypt)) else { return nil }
        return String(data: decryptedData, encoding: .utf8)
    }
    
    private func performCrypt(data: Data, operation: CCOperation) -> Data? {
        var outputLength = Int(0)
        var outputBytes = [UInt8](repeating: 0, count: data.count + kCCBlockSizeAES128)
        
        var keyBytes = [UInt8](repeating: 0, count: kCCKeySizeAES128)
        keyData.copyBytes(to: &keyBytes, count: kCCKeySizeAES128)
        
        var ivBytes = [UInt8](repeating: 0, count: kCCBlockSizeAES128)
        ivData.copyBytes(to: &ivBytes, count: kCCBlockSizeAES128)
        
        let cryptStatus = CCCrypt(operation,
                                  CCAlgorithm(kCCAlgorithmAES),
                                  CCOptions(kCCOptionPKCS7Padding),
                                  keyBytes,
                                  kCCKeySizeAES128,
                                  ivBytes,
                                  [UInt8](data),
                                  data.count,
                                  &outputBytes,
                                  outputBytes.count,
                                  &outputLength)
        
        if cryptStatus == kCCSuccess {
            return Data(bytes: outputBytes, count: outputLength)
        } else {
            print("加密/解密失败，状态码: \(cryptStatus)")
            return nil
        }
    }
    
    private func dataFromHex(_ hexString: String) -> Data? {
        var data = Data(capacity: hexString.count / 2)
        
        var hex = hexString
        while hex.count > 0 {
            let subIndex = hex.index(hex.startIndex, offsetBy: 2)
            let c = String(hex[..<subIndex])
            hex = String(hex[subIndex...])
            var ch: UInt32 = 0
            Scanner(string: c).scanHexInt32(&ch)
            var byte = UInt8(ch & 0xFF)
            data.append(&byte, count: 1)
        }
        
        return data
    }
}
